const diseaseDao = require('../dao/diseaseDao')
const disease = require('../models/disease');
const diseaseType = require('../models/diseaseType')

// 创建
exports.addDisease = async ctx => {
  let body = ctx.request.body;
  body.pv = 0
  // 处理要关联的对象
  let type = JSON.parse(body.type);
  let arr = [];
  type.map(async item => {
    const typeObj = await diseaseType.findOne({
      where: {
        id: item.value
      },
    });
    arr.push(typeObj)
  })
  // 创建
  const diseaseObj = await disease.create(body);
  // 建立关联
  await diseaseObj.setDiseaseTypes(arr)
  ctx.success('创建成功')
}

// 获取全部
exports.getAllDisease = async ctx => {
  let { p = 1,limit = 999 } = ctx.request.query
  let offset = (p - 1) * limit;
  let body = {
    offset:offset,
    limit:Number(limit)
  }
  const res = await diseaseDao.findAll(body);
  ctx.success('',res)
}

// 删除某条数据
exports.delDisease = async ctx => {
  let { id } = ctx.request.query
  const res = await diseaseDao.delById(id);
  ctx.success('删除成功')
}

// 更新
exports.updDisease = async ctx => {
  let body = ctx.request.body;
  await diseaseDao.upd(body);
  // 处理要关联的对象
  let type = JSON.parse(body.type);
  let arr = [];
  type.map(async item => {
    const typeObj = await diseaseType.findOne({
      where: {
        id: item.value
      },
    });
    arr.push(typeObj)
  })
  const diseaseObj = await diseaseDao.findById(body.id);
  // 建立关联
  await diseaseObj.setDiseaseTypes(arr)
  ctx.success('修改成功')
}

// 获取某类型下的所有疾病
exports.getDiseaseByType = async ctx => {
  let { type } = ctx.request.query
  const typeObj = await diseaseType.findOne({
    where: {
      id: type
    },
  });
  let res = await typeObj.getDiseases()
  ctx.success('',res)
}

// 获取详情
exports.getDiseaseDetail = async ctx => {
  let { id } = ctx.request.query
  const res = await diseaseDao.findById(id);
  const r = await diseaseDao.addPv(id)
  ctx.success('',res)
}

// 获取精选文章
exports.getMostPV = async ctx => {
  let res = await diseaseDao.getMostPV()
  ctx.success('',res)
}